import socket
import time
import threading
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(message)s')

def send_heartbeat(client_socket, serial_number, stop_event):
    while not stop_event.is_set():
        try:
            time.sleep(10)
            logging.info(f"Sending heartbeat for license {serial_number}")
            client_socket.send(f"HEARTBEAT {serial_number}".encode())
            response = client_socket.recv(1024).decode()
            if response != 'ALIVE':
                logging.warning("Heartbeat response not received. Connection might be lost.")
                stop_event.set()
        except Exception as e:
            logging.error(f"Error sending heartbeat: {e}")
            stop_event.set()

def connect_to_server(server_ip, server_port, serial_number):
    try:
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((server_ip, server_port))

        client_socket.send(f"VALIDATE {serial_number}".encode())
        response = client_socket.recv(1024).decode()
        if response == 'AUTHORIZED':
            logging.info("License validated. Starting software...")
            print("Software is running. Type 'exit' to quit.")

            stop_event = threading.Event()
            heartbeat_thread = threading.Thread(target=send_heartbeat, args=(client_socket, serial_number, stop_event))
            heartbeat_thread.start()

            while True:
                user_input = input("").strip().lower()
                if user_input == 'exit':
                    stop_event.set()
                    heartbeat_thread.join()

                    client_socket.send(f"EXIT {serial_number}".encode())
                    response = client_socket.recv(1024).decode()
                    if response == 'DISCONNECTED':
                        logging.info("Disconnected from server.")
                    break

        elif response == 'DENIED':
            logging.warning("License limit reached. Please try again later.")
        elif response == 'INVALID':
            logging.error("Invalid license key.")
        client_socket.close()
    except Exception as e:
        logging.error(f"Error connecting to server: {e}")

if __name__ == "__main__":
    print("Welcome to Software A")
    serial_number = input("Enter your license serial number: ")
    server_ip = '127.0.0.1'  
    server_port = 8080
    connect_to_server(server_ip, server_port, serial_number)
